package xyz.jcat.web;

import org.springframework.http.HttpStatus;
import xyz.jcat.common.util.JsonUtils;
import xyz.jcat.common.util.MapUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WebUtils {

    public static void writeJson(HttpServletResponse response, Object content) throws IOException {
        writeJson(response, new HashMap<>(0), content);
    }

    public static void writeJson(HttpServletResponse response, Map<String, String> headers, Object content) throws IOException {
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        if(MapUtils.isNotEmpty(headers)) {
            headers.forEach((k, v) -> {
                response.setHeader(k, v);
            });
        }
        response.getWriter().write(JsonUtils.toString(content));
    }

    public static void writeJson(HttpServletResponse response, HttpStatus httpStatus, Object content) throws IOException {
        writeJson(response, httpStatus, null, content);
    }

    public static void writeJson(HttpServletResponse response, HttpStatus httpStatus, Map<String, String> headers, Object content) throws IOException {
        response.setStatus(httpStatus.value());
        writeJson(response, headers, content);
    }
}
